package com.axinfu.util.validq.validator;

import com.axinfu.util.EmptyUtil;
import com.axinfu.util.validq.BaseValidator;
import com.axinfu.util.validq.ValidatorContext;
import com.axinfu.util.validq.exception.ValidQException;

/**
 * 验证String长度必须在min到max之间
 *
 * @author zjn
 * @since 2022/3/23
 */
@SuppressWarnings("unused")
public class StringLengthValidator extends BaseValidator {

    private Integer min = 0;
    private Integer max = Integer.MAX_VALUE;

    public StringLengthValidator() {
    }

    public StringLengthValidator(String field, String fieldName) {
        super(field, fieldName);
    }

    public StringLengthValidator(String field, String fieldName, String errorMsg) {
        super(field, fieldName, errorMsg);
    }

    @Override
    public int index() {
        return 5;
    }

    @Override
    public boolean validate(ValidatorContext context, Object target) {
        if (EmptyUtil.isEmpty(target)) {
            return true;
        }
        if (min <= 0) {
            throw new ValidQException("min greater than 0");
        }
        if (max <= 0) {
            throw new ValidQException("max greater than 0");
        }
        if (min > max) {
            throw new ValidQException("max greater than min");
        }

        String targetData = String.valueOf(target);

        if (targetData.trim().length() >= min && targetData.trim().length() <= max) {
            return true;
        }

        String errorMsg = null;
        if (targetData.trim().length() < min) {
            errorMsg = getDefaultMsg(String.format("[%s]长度不能小于[%s]", "%s", min));
        }
        if (targetData.trim().length() > max) {
            errorMsg = getDefaultMsg(String.format("[%s]长度不能大于[%s]", "%s", max));
        }

        return fail(context, target, errorMsg);
    }

    public Integer getMin() {
        return min;
    }

    public StringLengthValidator setMin(Integer min) {
        this.min = min;
        return this;
    }

    public Integer getMax() {
        return max;
    }

    public StringLengthValidator setMax(Integer max) {
        this.max = max;
        return this;
    }
}
